# Maven 自动安装脚本
Write-Host "开始下载和安装 Apache Maven..." -ForegroundColor Green

# 创建安装目录
$installDir = "C:\Program Files\Apache\maven"
if (!(Test-Path $installDir)) {
    New-Item -ItemType Directory -Path $installDir -Force
}

# 下载 Maven
$mavenVersion = "3.9.6"
$downloadUrl = "https://archive.apache.org/dist/maven/maven-3/$mavenVersion/binaries/apache-maven-$mavenVersion-bin.zip"
$zipFile = "$env:TEMP\apache-maven-$mavenVersion-bin.zip"

Write-Host "正在下载 Maven $mavenVersion..." -ForegroundColor Yellow
try {
    Invoke-WebRequest -Uri $downloadUrl -OutFile $zipFile
    Write-Host "下载完成！" -ForegroundColor Green
} catch {
    Write-Host "下载失败：$($_.Exception.Message)" -ForegroundColor Red
    exit 1
}

# 解压 Maven
Write-Host "正在解压 Maven..." -ForegroundColor Yellow
try {
    Expand-Archive -Path $zipFile -DestinationPath $installDir -Force
    Write-Host "解压完成！" -ForegroundColor Green
} catch {
    Write-Host "解压失败：$($_.Exception.Message)" -ForegroundColor Red
    exit 1
}

# 设置环境变量
$mavenHome = "$installDir\apache-maven-$mavenVersion"
Write-Host "正在设置环境变量..." -ForegroundColor Yellow

# 设置 MAVEN_HOME
[Environment]::SetEnvironmentVariable("MAVEN_HOME", $mavenHome, "User")

# 添加到 PATH
$currentPath = [Environment]::GetEnvironmentVariable("Path", "User")
$mavenBin = "$mavenHome\bin"
if ($currentPath -notlike "*$mavenBin*") {
    $newPath = "$currentPath;$mavenBin"
    [Environment]::SetEnvironmentVariable("Path", $newPath, "User")
}

# 刷新当前会话的环境变量
$env:MAVEN_HOME = $mavenHome
$env:Path = "$env:Path;$mavenBin"

Write-Host "Maven 安装完成！" -ForegroundColor Green
Write-Host "MAVEN_HOME: $mavenHome" -ForegroundColor Cyan
Write-Host "请重新启动 PowerShell 或运行以下命令刷新环境变量：" -ForegroundColor Yellow
Write-Host '$env:Path = [System.Environment]::GetEnvironmentVariable("Path","User")' -ForegroundColor Cyan

# 清理下载文件
Remove-Item $zipFile -Force

Write-Host "安装脚本执行完成！" -ForegroundColor Green